class Solution:
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        n = len(grid)
        if n == 0: return 0
        m = len(grid[0])
        if m == 0: return 0
        res = 0
        # 遍历每一个字符
        for i in range(n):
            for j in range(m):
                # 如果遍历字符是陆地"1"
                if grid[i][j] == "1":
                    res += 1
                    # 递归查找与这块陆地相连的所有陆地 并将他们改为零
                    self.change(grid, i, j)
        return res

    def change(self, grid, i, j):
        grid[i][j] = "0"
        # 判断上方字符
        if i > 0 and grid[i - 1][j] == "1":
            self.change(grid, i - 1, j)
        # 判断左方字符
        if j > 0 and grid[i][j - 1] == "1":
            self.change(grid, i, j - 1)
        # 判断下方字符
        if i < len(grid) - 1 and grid[i + 1][j] == "1":
            self.change(grid, i + 1, j)
        # 判断右方字符
        if j < len(grid[0]) - 1 and grid[i][j + 1] == "1":
            self.change(grid, i, j + 1)





# 根据矩阵中最长递增序列解法
class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if not grid:
            return 0
        dp = [[0] * len(grid[0]) for _ in range(len(grid))]
        self.res = 0
        def dfs(grid, dp, i, j):
            if grid[i][j] == '1':
                if not dp[i][j]:
                    self.res += 1
                    dp[i][j] = 1

                for dx, dy in zip((-1, 1, 0, 0), (0, 0, -1, 1)):
                    cur_x, cur_y = i + dx, j + dy

                    if -1 < cur_x < len(grid) and -1 < cur_y < len(grid[0]) and grid[cur_x][cur_y] =='1' and not dp[cur_x][cur_y]:
                        dp[cur_x][cur_y] = 1
                        dfs(grid, dp, cur_x, cur_y)
            else:
                dp[i][j] = 1

        for i in range(len(grid)):
            for j in range(len(grid[0])):
                dfs(grid, dp, i, j)
                
        return self.res